package com.qf.medicaldoctoradmin.healthMonitor.drugRemind.task;

import com.qf.common.entity.DrugSchedule;
import com.qf.medicaldoctoradmin.healthMonitor.drugRemind.dao.DrugScheduleDao;
import com.qf.medicaldoctoradmin.healthMonitor.drugRemind.service.DrugScheduleService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component
public class DrugScheduleTask {

    @Resource
    private DrugScheduleService drugScheduleService;

    @Resource
    private DrugScheduleDao drugScheduleDao;

    @Async
    // @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void checkDrugSchedules() {
        List<DrugSchedule> scheduleList = drugScheduleService.getEnableList();
        LocalTime now = LocalTime.now();

        for (DrugSchedule drugSchedule : scheduleList) {
            // 获取提醒时间 java.util.Date
            Date remindDate = drugSchedule.getRemindTime();
            // 将 Date 转换为 LocalTime
            LocalTime remindTime = remindDate.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalTime();

            // 仅在当前时间匹配提醒时间时发送提醒
            if (now.getHour() == remindTime.getHour() && now.getMinute() == remindTime.getMinute()) {
                sendReminder(drugSchedule);
            }
        }
    }

    private void sendReminder(DrugSchedule schedule) {
        System.out.printf("提醒: 请在 %s 服用药品 %s \n", schedule.getRemindTime(), schedule.getDrugName());
    }
}
